<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="person.name"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" oninput="if(value<0)value=0" v-model="person.age"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="person.sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="btnFn">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in user" :key="index">
          <td>{{index + 1}}</td>
          <td>{{item.name}}</td>
          <td>{{item.age}}</td>
          <td>{{item.sex}}</td>
          <td>
            <button @click="delBtn(index)">删除</button>
            <button @click="editBtn(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      user: [
        {
          name: 'yk',
          age: 23,
          sex: '男'
        }
      ],
      person: {
        name: '',
        age: null,
        sex: '男'
      },
      editIndex: -1,
    }
  },
  methods: {
    btnFn() {
      if(this.person.trim() === '' || this.person.age <= 0) {
        return alert('请输入合法数据')
      }
      if(this.editIndex > -1) {
        this.user.splice(this.editIndex, 1, {...this.person})
      }else {
        this.user.push({...this.person})
      }
      for(let k in this.person) {
        this.person[k] = ''
      }
      this.person.sex = '男'
    },
    delBtn(index) {
      this.user.splice(index, 1)
    },
    editBtn(index) {
      this.editIndex = index
      this.person = {...this.user[index]}
    }
  }
}
</script>
